<?php

namespace Think\Cache\Driver;

use Think\Cache;
use Think\Think;

defined('THINK_PATH') or exit();

/**
 * SAE KVDB缓存驱动
 * @category   Extend
 * @package  Extend
 * @subpackage  Driver.Cache
 * @author    ZXZ
 */
class Kvdb extends Cache {

    private $kvs = array();

    /**
     * 架构函数
     * @param array $options 缓存参数
     * @access public
     */
    function __construct($options = array()) {
        $this->options = $options;
        $this->options['expire'] = isset($options['expire']) ? $options['expire'] : C('DATA_CACHE_TIME');
        $this->options['prefix'] = 's_' . ( isset($options['prefix']) ? $options['prefix'] : C('DATA_CACHE_PREFIX'));
        $this->options['length'] = isset($options['length']) ? $options['length'] : 0;
        $this->handler = $this->_getKv(); //[sae] 下实例化
    }

    /**
     * 是否连接
     * @access private
     * @return boolean
     */
    private function isConnected() {
        //[sae] 下不用链接
        return TRUE;
    }

    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    public function get($name) {
        N('cache_read', 1);

        $name = $this->options['prefix'] . $name;

        if (!isset($this->kvs[$name])) {
            $data = $this->handler->get($name);
            $splPos = strpos($data, '-');

            /* 验证缓存是否过期 */
            $deadline = (int) substr($data, 0, $splPos);
            if ($deadline != 0 && time() > $deadline) {
                //缓存过期删除缓存
                $this->rm($name);
                return false;
            }

            $value = substr($data, $splPos + 1);
            $this->kvs[$name] = array(
                'value' => unserialize($value),
                'expire' => $deadline,
            );
        }

        return $this->kvs[$name]['value'];
    }

    /**
     * 写入缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value  存储数据
     * @param integer $expire  有效时间（秒）
     * @return boolean
     */
    public function set($name, $value, $expire = null) {
        N('cache_write', 1);

        /* 配置 */
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        $name = $this->options['prefix'] . $name;

        if ($expire > 0)
            $expire+=time();

        $this->kvs[$name] = array(
            'value' => $value,
            'expire' => $expire,
        );

        $data = $expire . '-' . serialize($value); //序列化以供存储
        if ($this->handler->set($name, $data)) {
            /* 队列 */
            if ($this->options['length'] > 0) {
                // 记录缓存队列
                $this->queue($name);
            }
            return true;
        }

        return false;
    }

    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function rm($name) {
        $name = $this->options['prefix'] . $name;

        unset($this->kvs[$name]);
        return $this->handler->delete($name);
    }

    /**
     * 清除缓存
     * @access public
     * @return boolean
     */
    public function clear() {
        $kv = $this->_getKv();
        $data = $kv->pkrget($this->options['prefix'], 100);
        foreach ($data as $key => $value) {
            $this->handler->delete($key);
        }

        if (count($data) >= 100)
            $this->clear();
        else
            return TRUE;
    }

    /**
     * 队列缓存
     * @access protected
     * @param string $key 队列名
     * @return mixed
     */
    //[sae] 下重写queque队列缓存方法
    protected function queue($key) {
        $queue_name = isset($this->options['queue_name']) ? $this->options['queue_name'] : 'think_queue';
        $value = F($queue_name);
        if (!$value) {
            $value = array();
        }
        // 进列
        if (false === array_search($key, $value))
            array_push($value, $key);
        if (count($value) > $this->options['length']) {
            // 出列
            $key = array_shift($value);
            // 删除缓存
            $this->rm($key);
            if (APP_DEBUG) {
                //调试模式下记录出队次数
                $counter = Think::instance('SaeCounter');
                if ($counter->exists($queue_name . '_out_times'))
                    $counter->incr($queue_name . '_out_times');
                else
                    $counter->create($queue_name . '_out_times', 1);
            }
        }
        return F($queue_name, $value);
    }

    /**
     * 获得SaeKv对象
     */
    private function _getKv() {
        static $kv;
        if (!$kv) {
            $kv = new \SaeKV();
            if (!$kv->init())
                E('您没有初始化KVDB，请在SAE管理平台初始化KVDB服务');
        }
        return $kv;
    }

}
